using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace MyClipboard
{
    class Clipboard
    {
        private const uint GHND = 0x0042;
        //
        [DllImport("kernel32.dll")]
        private static extern IntPtr GlobalAlloc(UInt32 uFlags, UInt32 dwBytes);
        [DllImport("kernel32.dll")]
        private static extern IntPtr GlobalFree(IntPtr hMem);
        [DllImport("kernel32.dll")]
        private static extern IntPtr GlobalLock(IntPtr hMem);
        [DllImport("kernel32.dll")]
        private static extern IntPtr GlobalUnlock(IntPtr hMem);
        [DllImport("Kernel32.dll", SetLastError = false)]
        private static extern void RtlMoveMemory(IntPtr dest, [MarshalAs(UnmanagedType.LPWStr)]string src, UInt32 size);
        //
        private const uint CF_UNICODETEXT = 13;
        //
        [DllImport("user32.dll")]
        private static extern bool OpenClipboard(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool CloseClipboard();
        [DllImport("user32.dll")]
        private static extern bool EmptyClipboard();
        [DllImport("user32.dll")]
        private static extern IntPtr SetClipboardData(UInt32 uFormat, IntPtr hMem);
        //
        public static bool string2Clipboard(IntPtr hWnd, string s)
        {
            bool isOk;
            IntPtr hMem = IntPtr.Zero;
            IntPtr MemPtr = IntPtr.Zero;
            UInt32 dwBytes = (UInt32)s.Length * 2;//Unicode
            //
            hMem = GlobalAlloc(GHND, dwBytes + 2);//+ \0
            if(IntPtr.Zero==hMem){
                return false;
            }
            MemPtr = GlobalLock(hMem);
            if (IntPtr.Zero == MemPtr)
            {
                GlobalFree(hMem);
                return false;
            }
            RtlMoveMemory(MemPtr, s, dwBytes);
            GlobalUnlock(hMem);
            if (false == OpenClipboard(hWnd))
            {
                GlobalFree(hMem);
                return false;
            }
            isOk = EmptyClipboard();
            SetClipboardData(CF_UNICODETEXT, hMem);
            isOk = CloseClipboard();
            //
            return true;
        }//
    }
}
